"""
sydo.py

Author: Harshad Sharma
2 March 2009
"""
import re
import os
import imp

try:
    from appuifw import *
    import e32
except:
    print "Program runs only on Python for S60!"


plugins = {}
commands = {}
plugin_directory = "E:\\Python\\plugins\\"
query_in_progress = False

def load_plugins():
    """Loads all plugins and the associated commands.
    Code borrowed from gtalkbot.py
    """
    global plugins, commands, plugin_directory
    re_plugin = re.compile('[^.].*\.py$')
    result = ""
    for plugin_file in os.listdir(plugin_directory):
        if re_plugin.match(plugin_file):
            name = plugin_file[:-3]
            plugin_info = imp.find_module(name, [plugin_directory])
            plugin = imp.load_module(name, *plugin_info)
            plugins[name] = plugin
            result += "%s, " %name
            # Load the commands supported by this plugin
            for command in plugin.commands():
                commands[command] = name

    return result[:-2]
    
def process(command, argument):
    try:
        plugin = plugins[commands[command]]
        return plugin.process(command, argument)
    except:
        return process('catchall', command + ' ' + argument)

def run():
    global query_in_progress
    if query_in_progress == False:
        query_in_progress = True
        text = query(u"Command:", "text")
        
        if text:
            text = text.strip().split(" ")
            command = text[0].lower()
            
            if command == "rlp":
                global plugins, commands
                
                plugins = {}
                commands = {}
                result = load_plugins()
                
            else:
                result = process(command, ' '.join(text[1:]))
                
            if result:
                note(unicode(result))
            
            query_in_progress = False
    
        app.focus = focus_checker
        hide()

def hide():
    import appswitch
    appswitch.switch_to_bg(u"sydo")

def focus_checker(foreground):
    if foreground:
        run()
    else:
        # think of something clever to put here?
        pass

if __name__ == "__main__":
    
    try:
        app.title = u"Sydo"
        load_plugins()
        run()            
        
    except:
        import traceback
        traceback.print_exc(file=open("e:\sydo.log","a"))
        note(u"Please check log file at E:\\sydo.log")